package cn.j0n4than.accountingtool.controller.common;

import cn.j0n4than.accountingtool.config.ResponseConfig;
import cn.j0n4than.accountingtool.service.ActiveService;
import cn.j0n4than.accountingtool.service.SpendingService;
import cn.j0n4than.accountingtool.service.TypeService;
import cn.j0n4than.accountingtool.service.UserService;
import cn.j0n4than.accountingtool.utils.DesUtil;
import cn.j0n4than.accountingtool.utils.MailUtil;
import cn.j0n4than.accountingtool.utils.RedisUtil;
import cn.j0n4than.accountingtool.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;

/**
 * 基控制器
 *
 * @author jonathan
 */
public class BaseController {

    /**
     * 激活服务
     *
     * @see cn.j0n4than.accountingtool.service.impl.ActiveServiceImpl
     */
    @Autowired
    protected ActiveService activeService;

    /**
     * 支出服务
     *
     * @see cn.j0n4than.accountingtool.service.impl.SpendingServiceImpl
     */
    @Autowired
    protected SpendingService spendingService;

    /**
     * 支出类型服务
     *
     * @see cn.j0n4than.accountingtool.service.impl.TypeServiceImpl
     */
    @Autowired
    protected TypeService typeService;

    /**
     * 用户服务
     *
     * @see cn.j0n4than.accountingtool.service.impl.UserServiceImpl
     */
    @Autowired
    protected UserService userService;

    /**
     * 数据加密工具类
     */
    @Autowired
    protected DesUtil desUtil;

    /**
     * JSON工具类
     */
    @Autowired
    protected ObjectMapper objectMapper;

    /**
     * 邮箱工具类
     */
    @Autowired
    protected MailUtil mailUtil;

    /**
     * redis工具类
     */
    @Autowired
    protected RedisUtil redisUtil;

    /**
     * 前端的网址
     */
    @Value("${site-url}")
    protected String siteUrl;

    /**
     * 获取验证器的错误
     *
     * @param response      Response实例
     * @param bindingResult 验证结果
     */
    protected void checkValidate(Response response, BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            assert bindingResult.getFieldError() != null;
            String message = bindingResult.getFieldError().getDefaultMessage();
            response.setStatus(ResponseConfig.ERROR);
            response.setMessage(message);
        }
    }

    /**
     * 获取客户端IP
     *
     * @param request HttpServletRequest
     * @return String IP
     */
    protected String getClientIp(HttpServletRequest request) {
        return request.getHeader("X-Real-IP");
    }
}
